#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Taotie Ren


# renameDates.py - Rename filenames with American MM-DD-YYYY date format to European DD-MM-YYYY

import shutil, os, re

# Create AmerEmailDateToEuro dir.
dirs = '.\\AmerEmailDateToEuro'
if not os.path.exists(dirs):
	os.makedirs(dirs)

# Create a regex that matches files with the American date format.
datePattern = re.compile(r"""^(.*?) # all text beforce the date
	((0|1)?\d) -                # one or two digits for the month
	((0|1|2|3)?\d) -            # one or two digits for the day
	((19|20)\d\d)               # four digits for the year
	(.*?)$                      # all text after the date
	""", re.VERBOSE)

# Loop over the files in the working directory.
for amerFilename in os.listdir('dirs'):
	mo = datePattern.search(amerFilename)

	# Skip files without a date.
	if mo == None:
		continue

		# Get the different parts of the filename.
		beforePart = mo.group(1)
		monthPart = mo.group(2)
		dayPart = mo.group(4)
		yearPart = mo.group(6)
		afterPart = mo.group(8)

	# datePattern = re.compile(r"""^(1)   # all text beforce the date
	# 	(2 (3) ) -                      # one or two digits for the month
	# 	(4 (5) ) -                      # one or two digits for the day
	# 	(6 (7) )                        # four digits for the year
	# 	(8)$                            # all text after the date
	# 	""", re.VERBOSE)

	# From the European-style filename.
	euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart

	# Get the full, absolute file paths.
	absWorkingDir = os.path.abspath('dirs')
	amerFilename = os.path.join(absWorkingDir, amerFilename)
	euroFilename = os.path.join(absWorkingDir, euroFilename)

	# Rename the files.
	print('Renaming "%s" to "%s" ...' % (amerFilename, euroFilename))
# shutil.move(amerFilename, euroFilename) # uncomment afer testing
